package com.jingdianjichi.subject.domain.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * Description:缓存工工具
 *
 * @Author dal
 * @Create 2024/6/1 17:58
 */
@Component
public class CacheUtil<K,V> {

//这段代码定义了一个私有的本地缓存对象localCache，
// 类型为Cache<String,String>，使用了Guava库中的CacheBuilder类进行构建。
// 该缓存的最大容量为5000，缓存项在写入10秒后过期。
    private Cache<String,String> localCache=
            CacheBuilder.newBuilder()
                    .maximumSize(5000)
                    .expireAfterWrite(10,
                            TimeUnit.SECONDS).build();
    public List<V> getResult(String cacheKey, Class<V> clazz,
                             Function<String, List<V>> function) {
          List<V> resultList= new LinkedList<>();
        String content = localCache.getIfPresent(cacheKey);

        if (StringUtils.isNotBlank(content)) {
            resultList = JSON.parseArray(content, clazz);
        }else {
            resultList=function.apply(cacheKey);
            if (!CollectionUtils.isEmpty(resultList)){
                localCache.put(cacheKey,JSON.toJSONString(resultList));
            }
        }
        return resultList;
    }

    public Map<K,V> getMapResult(String cacheKey, Class<V> clazz,
                               Function<String, Map<K,V>> function) {
      return new HashMap<>();
    }
}
